<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>WebSocket 示例</title>
</head>
<body>
<div class="container">
    <h2>WebSocket 示例</h2>
    <button id="connectBtn" class="btn btn-primary">连接</button>
    <button id="disconnectBtn" class="btn btn-danger">断开</button>
    <div class="mt-3">
        <label for="messageInput">输入消息：</label>
        <input type="text" id="messageInput" class="form-control" placeholder="输入消息">
        <button id="sendBtn" class="btn btn-success mt-2">发送消息</button>
    </div>
    <div class="mt-3">
        <h3>接收消息：</h3>
        <div id="messages"></div>
    </div>
</div>

<script>
    let websocket;

    document.getElementById('connectBtn').addEventListener('click', function () {
        websocket = new WebSocket("ws://127.0.0.1:6060/ws?userId=1");

        websocket.onopen = function () {
            console.log("WebSocket 连接成功");
        };

        websocket.onmessage = function (event) {
            console.log("收到消息：" + event.data);
            document.getElementById('messages').innerHTML += '<p>' + event.data + '</p>';
        };

        websocket.onclose = function () {
            console.log("WebSocket 连接关闭");
        };
    });

    document.getElementById('disconnectBtn').addEventListener('click', function () {
        if (websocket) {
            websocket.close();
        }
    });

    document.getElementById('sendBtn').addEventListener('click', function () {
        const message = document.getElementById('messageInput').value;
        if (websocket && websocket.readyState === WebSocket.OPEN) {
            websocket.send(message);
        }
    });
</script>
</body>
</html>